﻿using System.Collections.Generic;
using System.Linq;
using ZilLion.Core.DatabaseWrapper.SqlServer;
using ZilLion.Task.Domain.Entity;

namespace ZilLion.Task.Domain.Respository
{
    public class TaskStateRespository : SqlServerRespository<TaskStateEntity>
    {
        public TaskStateRespository()
        {
            Context = new TaskRunnerContext();
        }

        /// <summary>
        ///     获取当前serverid所有记录
        /// </summary>
        /// <returns></returns>
        public IList<TaskStateEntity> GetAllTaskRunLog(string nodeid = null)
        {
            if (nodeid.IsNotNullOrEmpty())
                return
                    GetList(@"select * from task_state where nodeid=@nodeid",
                        new { nodeid}).ToList();
            return GetList(@"select * from task_state "
            ).ToList();
        }

        /// <summary>
        ///     按ID 或者log
        /// </summary>
        /// <param name="taskid"></param>
        /// <param name="nodeid"></param>
        /// <returns></returns>
        public TaskStateEntity GetTaskRunLogById(string taskid, string nodeid = null)
        {
            if (nodeid.IsNotNullOrEmpty())

                return
                    GetList(@"select * from task_state where taskid=@taskid and nodeid=@nodeid",
                        new {nodeid, taskid}).FirstOrDefault();
            return GetList(@"select * from task_state where taskid=@taskid",
                new {nodeid, taskid}).FirstOrDefault();
        }


        /// <summary>
        ///     修改
        /// </summary>
        /// <param name="logEntity"></param>
        public void SaveTaskRunLog(TaskStateEntity logEntity)
        {
            var old = GetTaskRunLogById(logEntity.Taskid, logEntity.NodeId);
            if (old != null)
                Modify(logEntity);
            else
                Add(logEntity);
        }

        /// <summary>
        ///     删除
        /// </summary>
        /// <param name="logEntity"></param>
        public void RemoveTaskRunLog(TaskStateEntity logEntity)
        {
            Remove(logEntity);
        }
    }
}